package com.allenkerr.mail.util;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.io.IOException;

public class QiniuUtils {

    //设置好账号的ACCESS_KEY和SECRET_KEY
    private static final String ACCESS_KEY = "nMq5NmyPkrs9m3DNnIQwz9UYNL7RZjfFiTpCZ851";
    private static final String SECRET_KEY = "aWu51kgBcBBqEx-MhpSQm9oh9aGucRpnfjlFHRO1";

    //密钥配置
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    //创建上传对象
    private static final UploadManager uploadManager = new UploadManager(new Configuration(Zone.zone0()));

    /**
     * 获取 upToken
     *
     * @param bucketname
     * @return String
     */
    public String getUpToken(String bucketname) {
        return auth.uploadToken(bucketname);
    }

    /**
     * 上传文件
     *
     * @throws IOException
     */
    public void upload(String bucketName, String fileName, String filePath) throws IOException {
        try {
            //调用put方法上传
            Response response = uploadManager.put(filePath, fileName, getUpToken(bucketName));

            //打印返回的信息
            System.out.println(response.bodyString());
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) throws IOException {
        //要上传的空间
        String bucketName = "file-private";

        //上传到七牛后保存的文件名
        String fileName = "787.jpg";

        //上传文件的路径
        String filePath = "/Users/scw/Workspace/SpringBootDemo3/demo09-mail/src/main/resources/787.jpg";

        new QiniuUtils().upload(bucketName, fileName, filePath);
    }

}  